通过调用string :: c_str()返回的指针指向哪里?在下面的代码片段中,我想我会给出一个分段错误,但它给了我正确的输出.如果string :: c_str()返回的指针指向字符串对象内部的内部位置,那么当函数返回并调用对象析构函数时,我应该获得无效的内存访问.
#include <iostream>
#include <string>
using namespace std;
const char* func()
{
string str("test");
return str.c_str();
}
int main()
{
const char* p = func();
cout << p << endl;
return 0;
}
Output: test
Compiler: g++ 4.3.3
Platform: ubuntu 2.6.28-19
Run Code Online (Sandbox Code Playgroud) 我有一个永远不会被实例化的基类.这个基类有不同的子类.每个子类定义某些类变量,其中所有子类的名称相同,但值将不同.例如
class Base:
def display(self):
print self.logfile, self.loglevel
class d1(Base):
logfile = "d1.log"
loglevel = "debug"
def temp(self):
Base.display(self)
class d2(Base):
logfile = "d2.log"
loglevel = "info"
def temp(self):
Base.display(self)
Run Code Online (Sandbox Code Playgroud)
设计这个的正确方法是什么,以便我可以强制执行,如果明天定义任何新的子类,实现子类的人应该为这些类变量提供一些值而不是错过定义它们?