我在 C++/MFC 中有下面提到的函数:
CString StringFunc()
{
std::string abc = "Hello";
return abc.c_str();
}
int main()
{
CString Temp = StringFunc();
Use_Temp(Temp);
}
Run Code Online (Sandbox Code Playgroud)
1.) StringFunc() 返回的 abc.c_str() 指针的生命周期是多少,在 StringFunc() 返回后它会安全地复制到变量“Temp”吗?
2.) CString Temp = StringFunc() 是浅复制操作还是深复制?
在我的asp.net-mvc应用程序中,我有一个调用静态CreateContainer()方法的statis MvcApplication.
在这个方法中,我创建了我的统一ioc容器:
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.RegisterType<IConfigurationService, ConfigFile>();
container.RegisterType<ILoggerService, NlogLoggerService>();
container.RegisterInstance<ISearchService>(
new LuceneSearchService(
container.Resolve<IConfigurationService>(),
container.Resolve<ILoggerService>()),
new ContainerControlledLifetimeManager());
}
Run Code Online (Sandbox Code Playgroud)
如果我理解我的源代码,这应该给我一个单独的LuceneSearchService实例.然而,在我的日志记录中,我可以看到每次请求此实例时我的构造函数都会被命中.
我究竟做错了什么?
在C++中,可以将临时绑定到const引用:
struct A {};
int main() {
const A& a = A();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法为某个特定的A类禁用它,这样就不可能将这个类的临时值绑定到const引用?
我目前正在将我的代码转换为C++ 11并且在以下基于范围的for循环中遇到问题(FWIW,相同的代码在使用BOOST for_each之前运行得很好).
所述mLibraryFiles构件(STL向量)是一个单件实例的一部分,并且保证当呼叫者检查返回的对象只包含垃圾的方法返回后存在,但是.
通过它进行调试似乎在从方法返回之后从预期内容转为垃圾,所以我想我必须对C++ 11基于范围的循环实际如何工作有所不妥:
Entry* FindEntry(string inName)
{ Entry *rs = NULL;
for (auto libraryEntry : mLibraryFiles)
{
if (libraryEntry.filename.compare(inName) == 0)
{
rs = &libraryEntry;
break;
}
}
return rs;
}
Run Code Online (Sandbox Code Playgroud)
我原以为libraryEntry变量代表mLibraryFiles向量中的实际对象?
任何见解都非常感谢!
(编译器是LLVM 5.0虽然我怀疑这很重要..)
我想在运行时在main方法中创建一个未知数量的对象,每个对象都有一个特定的对象名.在程序结束之前,对象应该存在(main-method结束).请注意,在我的情况下,对象是Fields.
我想过这样的解决方案:
for ( i=1 ; i <= NumberOfObjects ; i++)
{
if (i==1)
{
MyClass *ObjectName1 = new MyClass();
}
if (i==2)
{
MyClass *ObjectName2 = new MyClass();
}
. //more if statements for more objects
.
.
} //for loop closed
Run Code Online (Sandbox Code Playgroud)
问题:
我不认为这个解决方案是好的,因为创建的对象的数量仍然限于for循环中的if语句.更好的解决方案?
循环中指针的范围:当退出if块时,指针超出范围.之后如何访问"新"创建的对象?
我有一个具有指针作为成员的结构:
struct MyStruct {
char *ptr;
}
Run Code Online (Sandbox Code Playgroud)
我想在一个范围内初始化 ptr,然后能够在该范围之外使用它:
{ // scope 0
{ //scope 1
{ // scope 2
mystruct.ptr = new char[100];
}
// mystruct.ptr still lives here
}
// i dont need mystruct anymore
delete[] mystruct.ptr;
}
Run Code Online (Sandbox Code Playgroud)
但后来我必须删除它,这很容易出错,我宁愿避免这样做。所以我想到使用std::shared_ptr.
{ // scope 0
{ //scope 1
{ // scope 2
auto a = std::make_shared<char>(new char[100]);
mystruct.ptr = a.get(); // ??????? HOW TO ASSIGN
}
// mystruct.ptr still SHOULD live here
}
}
Run Code Online (Sandbox Code Playgroud)
那么,我该怎么办呢?我应该如何将shared_ptr分配给mystruct.ptr以使所有权计数变为2?我看到 get() 不起作用,因为它只是传递指针但不给出所有权,因此它被删除。
如您所见,这里的主要动机是延长寿命,因此我对其他做法持开放态度。也许我在这里使用shared_ptr的想法是错误的?
内联创建并传递给方法的对象的生命周期是多少?例如:
myMethod(new String("Hello World"));
Run Code Online (Sandbox Code Playgroud)
字符串"Hello World"在myMethod执行后立即创建和销毁,或者它仍然保留在内存中,直到垃圾收集器将其删除?
我尝试使用正则表达式从字符串中获取所有非空白字符,但我不断回到相同的错误。
extern crate regex; // 1.0.2
use regex::Regex;
use std::vec::Vec;
pub fn string_split<'a>(s: &'a String) -> Vec<&'a str> {
let mut returnVec = Vec::new();
let re = Regex::new(r"\S+").unwrap();
for cap in re.captures_iter(s) {
returnVec.push(&cap[0]);
}
returnVec
}
pub fn word_n(s: &String, n: i32) -> &str {
let bytes = s.as_bytes();
let mut num = 0;
let mut word_start = 0;
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' || item == b'\n' {
num += 1;
if …Run Code Online (Sandbox Code Playgroud) struct A { //POD class
char data[10];
void print() {std::cout << data;}
};
int main() {
char buffer[11] = "HELLO"; //sets values in buffer
A* a = new(buffer)A;
a->print(); // read from memory buffer
a->~A();
}
Run Code Online (Sandbox Code Playgroud)
从类的角度来看,这是从未初始化的内存中读取,但从内存的角度来看,内存实际上是初始化的.这是不确定的行为,还是仅仅是危险的?
[注意:对于那些好奇的new(buffer)A和a->~A(),这被称为"placement new",用于在内存中的特定缓冲区中构造对象.这是vector在内部缓冲区构建类的掩护下的]
c++ placement-new object-lifetime undefined-behavior language-lawyer
#include <iostream>
#include <memory>
class Base
{
public:
virtual void foo() = 0;
};
class Derived : public Base
{
public:
void foo() override { std::cout << "Derived" << std::endl; }
};
class Concrete
{
public:
void Bar() { std::cout << "concrete" << std::endl; }
};
int main()
{
std::unique_ptr<Concrete> ConcretePtr = nullptr;
ConcretePtr->Bar();
std::unique_ptr<Base> BasePtr;
BasePtr->foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我假设将一个unique_ptr声明为具体类型Concrete,为类型的对象分配内存,Concrete而unique_ptr开始指向它.我的假设/理解是否正确?我问,因为ConcretePtr->Bar();打印机"混凝土"到控制台.但是,如果我创建一个指向接口的唯一指针Base,它不知道我需要的确切对象类型,也不知道在内存中分配/获取资源.
这失败BasePtr->foo();了BasePtr._Mypair._Myval2 was nullptr.
为什么第一个声明std::unique_ptr<Concrete> ConcretePtr = nullptr; …