这是一个简单的问题:
使用new运算符是否返回类型指针(void*)?请参阅new/delete和malloc/free之间的区别是什么?答案 - 它说new returns a fully typed pointer while malloc void *
但根据http://www.cplusplus.com/reference/new/operator%20new/
throwing (1)
void* operator new (std::size_t size) throw (std::bad_alloc);
nothrow (2)
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) throw();
placement (3)
void* operator new (std::size_t size, void* ptr) throw();
Run Code Online (Sandbox Code Playgroud)
这意味着它返回一个类型为(void*)的指针,如果它返回(void*)我从未见过像MyClass*ptr =(MyClass*)new MyClass这样的代码;
我很困惑.
编辑
根据http://www.cplusplus.com/reference/new/operator%20new/ example
std::cout << "1: ";
MyClass * p1 = new MyClass;
// allocates memory by calling: operator new (sizeof(MyClass))
// and then constructs an object …Run Code Online (Sandbox Code Playgroud) 我正在尝试用malloc和free替换operator new和delete(我有理由).问题显示在下面的代码中:
std::string *temp = (std::string *)malloc(sizeof(std::string) * 2); // allocate space for two string objects.
temp[0] = "hello!";
temp[1] = "world!";
for(int i = 0; i < 2; i++)
{
printf("%s\n", temp[i].c_str());
}
free(temp);
return 0; // causes SIGSEGV.
Run Code Online (Sandbox Code Playgroud)
然而..
std::string *temp = new std::string[2];
temp[0] = "hello!";
temp[1] = "world!";
for(int i = 0; i < 2; i++)
{
printf("%s\n", temp[i].c_str());
}
delete [] temp;
return 0; // works fine
Run Code Online (Sandbox Code Playgroud)
为什么?并且有人可以建议我用malloc和free替换这些运算符的正确方法是什么?
问候.
编辑:这只是一个例子,我没有使用标准的C++库.
编辑:这样的事情怎么样?
class myclass
{
public: …Run Code Online (Sandbox Code Playgroud)