strcpy? compiler problem..

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 
#ifndef STING_H
#define STRING_H
#include<iostream>
#include<cstring>
using namespace std;
class str{
	char *m_str;
	int m_len;
public:
	str(const char *s){
		cout << "constractor" << endl;
		m_len = strlen(s);
		m_str = new char[m_len + 1];
		strcpy(m_str, s);


	}
	~str(){
		cout << "destractor" << endl;
		delete[] m_str;
	}
	void set(const char* s){
		delete[]m_str;
		m_len = strlen(s);
		m_str = new char[m_len + 1];
		strcpy(m_str, s);
	}
	void print()const{
		if (m_str)
			cout << "m_str=" << m_str << "m_len" << m_len << endl;
	}
	

};
#endif 

main
1
2
3
4
5
6
7
#include<iostream>
#include "Header.h"
int main(){
	str s = "aaaa";
	s.print();

}



cant run it ..for some reason problem with strcpy that compiler make an error
i need some other libary or what?
closed account (48T7M4Gy)
Runs OK here using the cpp shell.

constractor
m_str=aaaam_len4
destractor
how come?
i have visual studio 2013

Error 1 error C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\users\darje\documents\visual studio 2013\projects\consoleapplication3\header.h 15 1 ConsoleApplication3
Last edited on
Since you have a set() method, you could implement the constructor using it. You just have to setup the members with some initial value. In this case, set() calls delete[] m_str, so m_str must be valid. You can set it to nullptr since delete and delete[] can safely be called with null pointers. Since set() doesn't use m_len, you could leave that uninitialized, but I'd initialize it anyway. After all, what if someone changes set() later on and the new version DOES use m_len? Your constructor would then break:
1
2
3
4
5
str(const char *s){
	m_str = nullptr;
	m_len = 0;
	set(s);
}
Better yet, use a member initializer list:
1
2
3
4
5
6
str(const char *s) :
	m_str(nullptr),
	m_len(0)
{
	set(s);
}


Topic archived. No new replies allowed.